package com.qyi.activemq.queue.producer;

import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.ScheduledMessage;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.jms.DeliveryMode;
import javax.jms.TextMessage;
import java.util.HashMap;
import java.util.Map;

/**
 * @author luqi
 * @Date 2021/3/11 10:07
 * @Description TODO
 */
@Service
@Slf4j
public class MqProducerService {

    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;

    /**
     * 延时发送
     *
     * @param msg
     */
    public void sendDelay(String msg) {
        msg = msg + "," + DateUtil.now();
        log.info("producer q2-delay:{}", msg);

        //延时 单位毫秒
        Map<String, Object> header = new HashMap<>(4);
        long delay = 5 * 1000;
        header.put(ScheduledMessage.AMQ_SCHEDULED_DELAY, delay);

        jmsMessagingTemplate.convertAndSend(new ActiveMQQueue("q2-delay"), msg, header);
    }

    /**
     * 重复发送
     *
     * @param msg
     */
    public void sendRepeat(String msg) {
        msg = msg + "," + DateUtil.now();
        log.info("producer q2-repeat:{}", msg);

        //重复
        Map<String, Object> header = new HashMap<>(4);
        long period = 1 * 1000;
        //重复3次 表示 一共执行4次
        int repeat = 3;
        header.put(ScheduledMessage.AMQ_SCHEDULED_PERIOD, period);
        header.put(ScheduledMessage.AMQ_SCHEDULED_REPEAT, repeat);

        jmsMessagingTemplate.convertAndSend(new ActiveMQQueue("q2-repeat"), msg, header);
    }


    /**
     * 重复发送
     *
     * @param msg
     */
    public void sendCorn(String msg) {
        msg = msg + "," + DateUtil.now();
        log.info("producer q2-corn:{}", msg);

        //定时任务
        Map<String, Object> header = new HashMap<>(4);
        //分 时 天 月 星期几
        String corn = "* * * * *";
        header.put(ScheduledMessage.AMQ_SCHEDULED_CRON, corn);

        jmsMessagingTemplate.convertAndSend(new ActiveMQQueue("q2-corn"), msg, header);
    }

}
